<template>
  <div class="login-page">
<van-nav-bar left-arrow class="back"/>
 <h3 class="title">短信登录</h3>
    <!-- 表单 -->
    <van-form ref="form">
      <van-field v-model="form.mobile" :rules="rules.mobile" placeholder="请输入手机号"></van-field>
     <van-field v-model="form.code" :rules="rules.code" center clearable placeholder="请输入短信验证码">
  <template #button>
    <van-button size="mini"  type="default" @click="play" class="yzm" :disabled="form.time > 0">{{form.time>0?`${form.time}秒后重新发送`:'发送验证码'}}</van-button>
  </template>
</van-field>
    </van-form>
  <van-button type="primary" size="large" color="#FC6627" class="loginBtn" @click="log">登录</van-button>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  name: 'LoginPage',
  methods: {
    login () {
      this.$refs.form.validate().then(() => {
        console.log('校验成功')
      })
    },
    async play () {
      const res = await axios.get(`http://toutiao.itheima.net/v1_0/sms/codes/${this.form.mobile}`)
      console.log(res)
      if (this.form.time > 0) { return }
      this.form.time = 60
      this.form.timerId = setInterval(() => {
        if (this.form.time > 0) {
          this.form.time--
        } else {
          clearInterval(this.form.timerId)
          this.form.timerId = null
        }
      }, 1000)
    },
    async log () {
      const res = await axios.post('http://toutiao.itheima.net/v1_0/authorizations', {
        mobile: this.form.mobile,
        code: this.form.code
      })
      console.log(res.status)
      if (res.status > 300) return this.$toast.fail('登录失败')
      if (res.status >= 200 && res.status < 300) {
        localStorage.setItem('token', res.data.data.token)
        location.href = '/home'
        return this.$toast.success('登录成功')
      }
    }
  },
  data () {
    return {
      form: {
        mobile: '',
        code: '',
        time: 0,
        tmierId: ''
      },
      rules: {
        mobile: [
          { required: true, message: '请输入手机号' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不对' }
        ],
        code: [
          { required: true, message: '请输入手机号' },
          { pattern: /^\d{6}$/, message: '验证码是6个数字' }
        ]
      }
    }
  }

}
</script>
<style scoped lang="less">
.login-page {
  padding: 0 32px;
  .back {
    height: 60px;
    display: flex;
    align-items: center;
    .geek-icon {
      font-size: 20px;
      color: #ccc;
      position: relative;
      left: -15px;
    }
  }
  .title {
    font-size: 22px;
    line-height: 1;
    padding: 30px 0;
  }
  .van-cell {
    padding: 20px 0;
    &::after{
      left: 0;
      right: 0;
    }
  }
  .back{
    margin-left: -20px;
  }
  .yzm{
    border: 0;
  }
  .loginBtn{
    margin-top: 40px;
  }

}
</style>
